//
//  FileUploadView.swift
//  AutoPrint
//
//  Created by David on 16/10/12.
//  Copyright © 2016年 fatcat. All rights reserved.
//  文件上传控制器

import UIKit

@objc protocol FileUploadViewDelegate {
    optional func textFieldScrollUp(textField: UITextField)
    optional func didUpdatePrice()
    optional func fileDidUploadFinish()
    optional func jumpToPreViewFile(onlineFile: Bool, filePath: String, fileName: String)
}

class FileUploadView: NSObject, NSURLSessionDataDelegate {
    
    var filePath: String?
    var fileName: String?
    var fileSize: String?
    var fileMD5: String?
    var fileID: String?
    
    var fileType: String?
    
    var remoteFileName: String?
    
    var numOfPage:Int{
        get {
            return pageNum
        }
    }
    
    var numOfQuantity:Int{
        get {
            return quantity
        }
    }
    
    private var pageNum:Int = 0
    private var quantity: Int = 1
    private var uploadFinished = false
    var isFinishedUpload:Bool{
        get{
            return uploadFinished
        }
    }
    
    var upload: NSURLSessionDataTask!
    
    var uploadView: UIView?
    var progressView: UIProgressView!
    var retryUploadBtn: UIButton!
    var previewBtn: UIButton!
    
    var pageNumView: UIView?
    var pageNumLabel: UILabel!
    
    var quantityView: UIView?
    var quantityIndicator: UITextField!
    var quantityAdjustor: UIStepper!
    
    var optionView: UIView?
    var singleDoublePageOption = 1
    var blackWhiteColorOption = 1
    var singleDoublePageSelect: UISegmentedControl!
    var blackWhiteColorSelect: UISegmentedControl!
    
    var delegate: FileUploadViewDelegate?
    
    
    init(file: UDFile) {
        
        self.filePath = file.filePath
        self.fileName = file.fileName
        self.fileSize = file.fileSize
        self.fileMD5 = file.fileMD5
        
        progressView = UIProgressView(progressViewStyle: .Default)
        progressView.progress = 0.05
        
        retryUploadBtn = UIButton()
        retryUploadBtn.setTitleColor(Fatcat.SELECTED_COLOR, forState: .Normal)
        retryUploadBtn.layer.borderColor = Fatcat.SELECTED_COLOR.CGColor
        retryUploadBtn.layer.borderWidth = 1
        retryUploadBtn.layer.cornerRadius = 4
        
        pageNumLabel = UILabel()
        pageNumLabel.textColor = UIColor.lightGrayColor()
        pageNumLabel.textAlignment = .Right
        pageNumLabel.text = "0"
        
        quantityAdjustor = UIStepper()
        quantityIndicator = UITextField()
        
        previewBtn = UIButton()
        previewBtn.setTitleColor(Fatcat.SELECTED_COLOR, forState: .Normal)
        previewBtn.layer.borderColor = Fatcat.SELECTED_COLOR.CGColor
        previewBtn.layer.borderWidth = 1
        previewBtn.layer.cornerRadius = 4
        previewBtn.alpha = 0
    }
    
    func createUploadView(frame: CGRect) -> UIView{
        if uploadView == nil {
            uploadView = UIView(frame: frame)
            
            let icon = UIImageView(frame: CGRect(x: 16, y: 8, width: 48, height: 48))
            icon.backgroundColor = UIColor.lightGrayColor()
            uploadView!.addSubview(icon)
            
            fileType = fileName!.componentsSeparatedByString(".").last
            if fileType != nil {
                if fileType == "doc" || fileType == "docx" {
                    icon.backgroundColor = UIColor.clearColor()
                    icon.image = UIImage(named: "documents_icon_doc")
                }else if fileType == "xls" || fileType == "xlsx" {
                    icon.backgroundColor = UIColor.clearColor()
                    icon.image = UIImage(named: "documents_icon_xls")
                }else if fileType == "ppt" || fileType == "pptx" {
                    icon.backgroundColor = UIColor.clearColor()
                    icon.image = UIImage(named: "documents_icon_ppt")
                }else if fileType == "pdf"{
                    icon.backgroundColor = UIColor.clearColor()
                    icon.image = UIImage(named: "documents_icon_pdf")
                }else if fileType == "txt"{
                    icon.backgroundColor = UIColor.clearColor()
                    icon.image = UIImage(named: "documents_icon_txt")
                }else if fileType == "png" || fileType == "jpg" || fileType == "jpeg" || fileType == "bmp" {
                    pageNumLabel.text = "1"
                    pageNum = 1
                    icon.contentMode = .ScaleAspectFill
                    icon.layer.masksToBounds = true
                    if filePath != nil {
                        icon.image = UIImage(contentsOfFile: filePath!)
                    }
                    
                }
            }
            
            let fileNameLabel = UILabel(frame: CGRect(x: 72, y: 8, width: (frame.width - 72)/2, height: 20))
            fileNameLabel.lineBreakMode = .ByTruncatingMiddle
            uploadView!.addSubview(fileNameLabel)
            
            let fileSizeLabel = UILabel(frame: CGRect(x: 72, y: 36, width: (frame.width - 72)/2, height: 20))
            fileSizeLabel.textColor = UIColor.lightGrayColor()
            uploadView!.addSubview(fileSizeLabel)
            
            progressView.frame =  CGRect(x: frame.width/2 + 48, y: 32, width: (frame.width - 64)/2 - 32, height: 8)
            
            
            retryUploadBtn.frame = CGRect(x: frame.width/2 + 48, y: 16, width: (frame.width - 64)/2 - 32, height: 32)
            retryUploadBtn.alpha = 0
            retryUploadBtn.setTitle("重试", forState: .Normal)
            retryUploadBtn.addTarget(self, action: #selector(FileUploadView.retryUpload), forControlEvents: .TouchUpInside)
            
            uploadView!.addSubview(progressView)
            
            uploadView!.addSubview(retryUploadBtn)
            
            previewBtn.frame = CGRect(x: frame.width/2 + 48, y: 16, width: (frame.width - 64)/2 - 32, height: 32)
            
            previewBtn.setTitle("预览", forState: .Normal)
            previewBtn.addTarget(self, action: #selector(FileUploadView.previewFile), forControlEvents: .TouchUpInside)
            uploadView?.addSubview(previewBtn)
            
            fileNameLabel.text = fileName
            fileSizeLabel.text = fileSize
            
            let sep = UIView(frame: CGRect(x: 16, y: 63.5, width: frame.width-16, height: 0.5))
            sep.backgroundColor = UIColor.lightGrayColor()
            uploadView?.addSubview(sep)
        }
        
        
        return uploadView!
    }
    
    func createPageNumView(frame: CGRect) ->UIView{
        if pageNumView == nil {
            pageNumView = UIView(frame: frame)
            let textLabel = UILabel(frame: CGRect(x: 16, y: 8, width: (frame.width-36)/2, height: 28))
            pageNumView!.addSubview(textLabel)
            
            pageNumLabel.frame = CGRect(x: frame.width/2, y: 8, width: (frame.width-28)/2, height: 28)
            pageNumView!.addSubview(pageNumLabel)
            
            // MARK: 页数
            textLabel.text = "文档页数"
            
            
            let sep = UIView(frame: CGRect(x: 16, y: frame.height - 0.5, width: frame.width-16, height: 0.5))
            sep.backgroundColor = UIColor.lightGrayColor()
            pageNumView?.addSubview(sep)
        }
        return pageNumView!
    }
    
    func createQuantityView(frame: CGRect, index: Int) ->UIView{
        if quantityView == nil {
            quantityView = UIView(frame: frame)
            let textLabel = UILabel(frame: CGRect(x: 16, y: 8, width: (frame.width-36)/2, height: 28))
            quantityView!.addSubview(textLabel)
            
            quantityAdjustor.frame = CGRect(x: frame.width - 108, y: 8, width: 0, height: 0)
            quantityAdjustor.minimumValue = 1
            quantityAdjustor.stepValue = 1
            quantityView!.addSubview(quantityAdjustor)
            
            quantityIndicator.frame = CGRect(x: frame.width - 152, y: 8, width: 36, height: 28)
            quantityIndicator.tag = index
            quantityIndicator.text = "1"
            quantityIndicator.backgroundColor = UIColor(red: 244.0/255.0, green: 244.0/255.0, blue: 244.0/255.0, alpha: 1)
            quantityIndicator.textAlignment = .Center
            //                quantityIndicator.textColor = UIColor.lightGrayColor()
            quantityIndicator.keyboardType = .NumberPad
            quantityView!.addSubview(quantityIndicator)
            
            textLabel.text = "打印份数"
            quantityAdjustor.addTarget(self, action: #selector(FileUploadView.changeQuantity(_:)), forControlEvents: .ValueChanged)
            quantityIndicator.addTarget(self, action: #selector(FileUploadView.textFieldScrollUp(_:)), forControlEvents: .EditingDidBegin)
            quantityIndicator.addTarget(self, action: #selector(FileUploadView.quantityUpdate(_:)), forControlEvents: .EditingChanged)
            quantityIndicator.addTarget(self, action: #selector(FileUploadView.quantityRestore(_:)), forControlEvents: .EditingDidEnd)
            
            let seperator = UIView(frame: CGRect(x: 0, y: frame.height, width: frame.width, height: 8))
            seperator.backgroundColor = UIColor(red: 239.0/255.0, green: 239.0/255.0, blue: 244.0/255.0, alpha: 1)
            quantityView?.addSubview(seperator)
            
        }
        return quantityView!
    }
    
    func createOptionView(frame: CGRect) -> UIView{
        if optionView == nil{
            optionView = UIView(frame: frame)
            
            singleDoublePageSelect = UISegmentedControl(frame: CGRect(x: 16, y: 8, width: 120, height: 28))
            singleDoublePageSelect.tag = 1
            singleDoublePageSelect.insertSegmentWithTitle("单面", atIndex: 0, animated: false)
            singleDoublePageSelect.insertSegmentWithTitle("双面", atIndex: 1, animated: false)
            singleDoublePageSelect.selectedSegmentIndex = 0
            optionView?.addSubview(singleDoublePageSelect)
            singleDoublePageSelect.addTarget(self, action: #selector(FileUploadView.changeOption(_:)), forControlEvents: .ValueChanged)
            if fileType == "png" || fileType == "jpg" || fileType == "jpeg" || fileType == "bmp" {
                singleDoublePageSelect.enabled = false
            }
            
            blackWhiteColorSelect = UISegmentedControl(frame: CGRect(x: frame.width-136, y: 8, width: 120, height: 28))
            blackWhiteColorSelect.tag = 2
            blackWhiteColorSelect.insertSegmentWithTitle("黑白", atIndex: 0, animated: false)
            blackWhiteColorSelect.insertSegmentWithTitle("彩色", atIndex: 1, animated: false)
            blackWhiteColorSelect.selectedSegmentIndex = 0
            optionView?.addSubview(blackWhiteColorSelect)
            blackWhiteColorSelect.addTarget(self, action: #selector(FileUploadView.changeOption(_:)), forControlEvents: .ValueChanged)
            
            let sep = UIView(frame: CGRect(x: 16, y: frame.height - 0.5, width: frame.width-16, height: 0.5))
            sep.backgroundColor = UIColor.lightGrayColor()
            optionView?.addSubview(sep)
        }
        return optionView!
    }
    
    func checkFile(){
        //uploadFile()
        //return
        if fileMD5 == nil{
                
            let cfilepath = self.filePath! as CFString
            self.fileMD5 = FileMD5.FileMD5HashCreateWithPath(cfilepath).takeRetainedValue() as NSString as String
                
               
        }
        
        let resq = NSMutableURLRequest(URL: NSURL(string: "\(Fatcat.SERVER_DOMAIN_NAME)\(Fatcat.FILE_API)")!)
        resq.HTTPMethod = "POST"
        let cookies = NSHTTPCookieStorage.sharedHTTPCookieStorage().cookies!
        let cookiesHeader = NSHTTPCookie.requestHeaderFieldsWithCookies(cookies)
        resq.setValue(cookiesHeader["Cookie"], forHTTPHeaderField: "Cookie")
        resq.HTTPBody = NSString(string: "act=checkFile&fileMd5=\(fileMD5!)").dataUsingEncoding(NSUTF8StringEncoding)
        NSURLSession.sharedSession().dataTaskWithRequest(resq, completionHandler: { (reData:NSData?, resp:NSURLResponse?, err:NSError?) in
            var failed = true
            if err == nil{
                if let data = reData {
                    print("\(self.fileName)|\(NSString(data: data, encoding: NSUTF8StringEncoding))")
                    let jsonObj = try? NSJSONSerialization.JSONObjectWithData(data, options: .AllowFragments) as! NSDictionary
                    if jsonObj != nil{
                        let reCode = jsonObj?.objectForKey("code") as! Int
                        if reCode == 200 {
                            failed = false
                            dispatch_async(dispatch_get_main_queue(), {
                                self.finishUploadGetPage(jsonObj!)
                            })
                        }else if reCode == 201 {
                            let msg = jsonObj?.objectForKey("message") as! String
                            if msg == "文件不存在" {
                                if self.fileSize != "在线文件"{
                                    failed = false
                                    dispatch_async(dispatch_get_main_queue(), {
                                        self.uploadFile()
                                    })
                                }
                                
                            }
                            
                            
                        }
                    }else{
                        print("json Error")
                    }
                    
                    
                }
            }
            if failed {
                dispatch_async(dispatch_get_main_queue(), {
                    self.progressView.alpha = 0
                    self.retryUploadBtn.alpha = 1
                })
            }
        }).resume()
        
        
    }
    
    func uploadFile(){
        let resq = NSMutableURLRequest(URL: NSURL(string: "\(Fatcat.SERVER_DOMAIN_NAME)\(Fatcat.FILE_API)")!)
        resq.HTTPMethod = "POST"
        let cookies = NSHTTPCookieStorage.sharedHTTPCookieStorage().cookies!
        let cookiesHeader = NSHTTPCookie.requestHeaderFieldsWithCookies(cookies)
        resq.setValue(cookiesHeader["Cookie"], forHTTPHeaderField: "Cookie")
        
        let postData = NSMutableData()
        //act=uploadFile&pNum=&isShare=&cId=&printFile
        
        resq.setValue("multipart/form-data; boundary=AaB03x", forHTTPHeaderField: "Content-Type")
        postData.appendData(NSString(string: "--AaB03x\r\nContent-Disposition: form-data; name=\"act\";\r\n\r\nuploadFile\r\n").dataUsingEncoding(NSUTF8StringEncoding)!)
        //postData.appendData(NSString(string: "--AaB03x\r\nContent-Disposition: form-data; name=\"pNum\";\r\n\r\n1\r\n").dataUsingEncoding(NSUTF8StringEncoding)!)
        postData.appendData(NSString(string: "--AaB03x\r\nContent-Disposition: form-data; name=\"isShare\";\r\n\r\n0\r\n").dataUsingEncoding(NSUTF8StringEncoding)!)
        postData.appendData(NSString(string: "--AaB03x\r\nContent-Disposition: form-data; name=\"cId\";\r\n\r\n1\r\n").dataUsingEncoding(NSUTF8StringEncoding)!)
        // printFile 文件字段
        
        let fileData = NSData(contentsOfFile: filePath!)
        
        postData.appendData(NSString(string: "--AaB03x\r\nContent-Disposition: form-data; name=\"printFile\"; filename=\"\(fileName!)\"\r\nContent-Type: image/jpeg\r\n\r\n").dataUsingEncoding(NSUTF8StringEncoding)!)
        postData.appendData(fileData!)
        
        postData.appendData(NSString(string: "\r\n--AaB03x--\r\n").dataUsingEncoding(NSUTF8StringEncoding)!)
        resq.setValue(String(postData.length), forHTTPHeaderField: "Content-Length")
        resq.HTTPBody = postData
        
        
        let session = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration(), delegate: self, delegateQueue: NSOperationQueue())
        
        upload = session.dataTaskWithRequest(resq) { (reData:NSData?, resp:NSURLResponse?, err:NSError?) in
            var failed = true
            if err == nil {
                if let data = reData {
                    print("\(self.fileName)|\(NSString(data: data, encoding: NSUTF8StringEncoding))")
                    let jsonObj = try? NSJSONSerialization.JSONObjectWithData(data, options: .AllowFragments) as! NSDictionary
                    if jsonObj != nil{
                        if jsonObj?.objectForKey("code") as! Int == 200 {
                            // MARK: 上传结果处理
                            failed = false
                            dispatch_async(dispatch_get_main_queue(), {
                                self.finishUploadGetPage(jsonObj!)
                                
                                
                            })
                        }
                    }
                    
                }
            }
            if failed {
                dispatch_async(dispatch_get_main_queue(), {
                    self.progressView.alpha = 0
                    self.retryUploadBtn.alpha = 1
                })
            }
        }
        
        upload.resume()
        
    }
    
    func URLSession(session: NSURLSession, task: NSURLSessionTask, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) {
        //print("\(totalBytesSent)|\(totalBytesExpectedToSend)")
        // MARK: 更新进度条
        dispatch_async(dispatch_get_main_queue()) {
            self.progressView.setProgress(Float(totalBytesSent)/Float(totalBytesExpectedToSend), animated: true)
        }
    }
    
    func retryUpload(){
        progressView.progress = 0.05
        progressView.alpha = 1
        retryUploadBtn.alpha = 0
        //checkFile()
        uploadFile()
    }

    func changeQuantity(sender: UIStepper){
        quantity = Int(sender.value)
        quantityIndicator.text = "\(Int(sender.value))"
        delegate?.didUpdatePrice?()
    }
    func quantityUpdate(sender: UITextField){
        if sender.text != "" {
            if let quantity = Int(sender.text!) {
                if 0 < quantity && quantity < 100{
                    self.quantity = quantity
                    quantityAdjustor.value = Double(quantity)
                }
                
            }
            sender.text = "\(quantity)"
            delegate?.didUpdatePrice?()
        }
        
    }
    func quantityRestore(sender: UITextField){
        if sender.text == "" {
            sender.text = "1"
            quantity = 1
            quantityAdjustor.value = 1
            delegate?.didUpdatePrice?()
        }
    }
    func textFieldScrollUp(sender: UITextField){
        delegate?.textFieldScrollUp?(sender)
    }
    func finishUploadGetPage(info: NSDictionary){
        // MARK: 上传完成，获取文件id和页数
        
        let data = info.objectForKey("data") as? NSDictionary
        if data != nil {
            
            var fid = data?.objectForKey("id") as? String
            if fid == nil {
                fid = "\(data?.objectForKey("id") as! Int)"
            }
            fileID = fid
            
            let fileName = data?.objectForKey("fileName") as? String
            let fileMd5 = data?.objectForKey("fileMd5") as? String
            
            self.remoteFileName = fileName
            self.fileMD5 = fileMd5
            
            if remoteFileName != nil{
                if self.fileType == "png" || self.fileType == "jpg" || self.fileType == "jpeg" || self.fileType == "bmp" {
                    self.uploadFinished = true
                    self.progressView.alpha = 0
                    self.previewBtn.alpha = 1
                    
                    self.delegate?.didUpdatePrice?()
                }else{
                    getFilePage()
                }
                
            }else{
                self.progressView.alpha = 0
                self.retryUploadBtn.alpha = 1
            }
            
            
        }
        
    }
    
    func getFilePage(){
        
        let getPageResq = NSMutableURLRequest(URL: NSURL(string: "\(Fatcat.SERVER_DOMAIN_NAME)\(Fatcat.FILE_API)")!)
        getPageResq.HTTPMethod = "POST"
        getPageResq.HTTPBody = "act=getPageNum&fileName=\(remoteFileName!)".dataUsingEncoding(NSUTF8StringEncoding)
        NSURLSession.sharedSession().dataTaskWithRequest(getPageResq, completionHandler: { (data:NSData?, resp:NSURLResponse?, err:NSError?) in
            var failed = true
            if err == nil{
                if data != nil{
                    print(String(data: data!, encoding: NSUTF8StringEncoding))
                    let jsonObj = try? NSJSONSerialization.JSONObjectWithData(data!, options: .AllowFragments)
                    if jsonObj != nil {
                        let jsonDic = jsonObj as? NSDictionary
                        if jsonDic != nil{
                            let code = jsonDic?.objectForKey("code") as! Int
                            if code == 200 {
                                failed = false
                                let pNumData = jsonDic?.objectForKey("data") as? NSDictionary
                                var pNum = pNumData?.objectForKey("pages") as? Int
                                if pNum == nil {
                                    pNum = Int(pNumData?.objectForKey("pages") as! String)!
                                }
                                
                                dispatch_async(dispatch_get_main_queue(), {
                                    
                                    
                                    self.uploadFinished = true
                                    self.progressView.alpha = 0
                                    self.previewBtn.alpha = 1
                                    
                                    self.pageNum = pNum!
                                    self.pageNumLabel.text = "\(self.pageNum)"
                                    self.delegate?.didUpdatePrice?()
                                })
                            }
                            
                        }
                    }
                }
            }
            if failed {
                dispatch_async(dispatch_get_main_queue(), {
                    self.progressView.alpha = 0
                    self.retryUploadBtn.alpha = 1
//                    NSTimer.scheduledTimerWithTimeInterval(3, target: self, selector: #selector(FileUploadView.getFilePage), userInfo: nil, repeats: false)
                })
            }
        }).resume()
    }
    
    func previewFile(){
        // MARK: 判断本地还是在线，然后打开预览
        if fileSize == "在线文件" {
            delegate?.jumpToPreViewFile?(true, filePath: filePath!, fileName: fileName!)
        }else{
            delegate?.jumpToPreViewFile?(false, filePath: filePath!, fileName: fileName!)
        }
    }
    func changeOption(sender: UISegmentedControl){
        switch sender.tag {
        case 1:
            singleDoublePageOption = sender.selectedSegmentIndex + 1
            // MARK: 单面双面 黑白彩印 价格不同
            delegate?.didUpdatePrice?()
            break
        case 2:
            blackWhiteColorOption = sender.selectedSegmentIndex + 1
            delegate?.didUpdatePrice?()
            break
        default:
            break
        }
    }
    
    func cancelUpload(){
        upload.suspend()
    }
    /*
    // Only override drawRect: if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    override func drawRect(rect: CGRect) {
        // Drawing code
    }
    */

}

class UDFile {
    var filePath: String?
    var fileName: String?
    var fileSize: String?
    var fileMD5:String?
    
    init(filePath: String?, fileName: String?, fileSize: String?, fileMD5: String?){
        self.filePath = filePath
        self.fileName = fileName
        self.fileSize = fileSize
        self.fileMD5 = fileMD5
    }
}
